package com.educate.controller;

import cn.hutool.core.map.MapUtil;
import com.educate.common.api.Result;
import com.educate.pojo.User;
import com.educate.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;

/**
 * @author yjj
 * @date 2021/11/8
 * @description: 用户Controller
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 注册新用户(学生)
     */
    @ApiOperation("注册新用户(学生)")
    @PostMapping("/register")
    public Result register(@ApiParam(value = "用户名",required = true) @RequestParam("username") @Validated String username, @ApiParam(value = "密码",required = true) @RequestParam("password") @Validated String password) {
        User user = userService.getUserInfoByUsername(username);
        if(user != null){
            return Result.failed("此账号重复,请重试！");
        }
        int flag =  userService.registerNewUser(username,password);
        if(flag == 0)
            return Result.failed("注册失败");
        return Result.success("注册成功！");
    }
    /**
     * 用户头像和姓名
     */
    @ApiOperation("获取用户头像和姓名")
    @GetMapping("/minUser")
    public Result getMinUserInfo(Principal principal){
        String username = principal.getName();
        User user = userService.getUserInfoByUsername(username);
        String avatar = user.getAvatar();
        String fullName = user.getFullName();
        return Result.success(
                MapUtil.builder()
                .put("username",username)
                .put("avatar",avatar)
                .put("fullName",fullName)
                .build());
    }
}
